package com.mk.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.annotation.AuthCheck;
import com.mk.api.imagesearch.ImageSearchApiFacade;
import com.mk.api.imagesearch.model.ImageSearchResult;
import com.mk.common.*;
import com.mk.contants.UserConstant;
import com.mk.exception.BusinessException;
import com.mk.exception.ErrorCode;
import com.mk.exception.ThrowUtils;
import com.mk.model.dto.picture.*;
import com.mk.model.entity.Picture;
import com.mk.model.entity.Space;
import com.mk.model.entity.User;
import com.mk.model.enums.PictureReviewStatusEnum;
import com.mk.model.vo.picture.PictureTagCategory;
import com.mk.model.vo.picture.PictureVO;
import com.mk.service.PictureService;
import com.mk.service.SpaceService;
import com.mk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Autowired
    private PictureService pictureService;

    @Autowired
    private UserService userService;

    @Autowired
    private CacheUtils cacheUtils;

    @Autowired
    private SpaceService spaceService;



    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @AuthCheck(UserConstant.DEFAULT_ROLE)
    @PostMapping("/upload")
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadRequest pictureUploadRequest) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);
        // 获取当前登录用户
        User user = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        PictureVO pictureVO = pictureService.uploadPicture(pictureUploadRequest, multipartFile, user);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    @AuthCheck(UserConstant.DEFAULT_ROLE) // 必须登录
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest) {
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        String fileUrl = pictureUploadRequest.getFileUrl();
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "Url不能为空");
        PictureVO pictureVO = pictureService.uploadPicture(pictureUploadRequest, fileUrl, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量抓取上传图片
     * @param byBatchRequest
     * @return
     */
    @AuthCheck(UserConstant.ADMIN_ROLE)
    @PostMapping("/upload/batch")
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest byBatchRequest){
        ThrowUtils.throwNotNull(byBatchRequest);
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        Integer uploadCount = pictureService.uploadPictureByBatch(byBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }


    /**
     * 删除图片
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deletePictureById(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwNotNull(deleteRequest);
        // 获取登录用户
        User loginUser = userService.getCurrentLoginUser();
        pictureService.deletePicture(deleteRequest.getId(), loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     *
     * @return
     */
    @AuthCheck(UserConstant.ADMIN_ROLE)
    @PostMapping("/update")
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest updateRequest) {
        ThrowUtils.throwNotNull(updateRequest);
        validId(updateRequest.getId());
        // 封装Picture对象信息
        Picture picture = new Picture();
        BeanUtils.copyProperties(updateRequest, picture);
        List<String> tags = updateRequest.getTags();
        picture.setTags(JSONUtil.toJsonStr(tags));
        // 检验picture
        pictureService.validPicture(picture);
        // 判断是否存在
        Picture oldPicture = pictureService.getById(updateRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        // 填充审核信息
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        pictureService.fillReviewParams(picture, loginUser);
        // 执行更新操作
        boolean b = pictureService.updateById(picture);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取图片信息（仅管理员可用）
     * @param id
     * @return
     */
    @AuthCheck(UserConstant.ADMIN_ROLE)
    @GetMapping("/get")
    public BaseResponse<Picture> getPictureById(Long id) {
        validId(id);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(picture);
    }

    /**
     * 根据id获取图片（VO封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVoById(Long id) {
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        // 封装VO类
        PictureVO pictureVo = pictureService.getPictureVOById(id, loginUser);
        return ResultUtils.success(pictureVo);
    }

    /**
     * 分页获取图片列表 （仅管理员可用） (admin)
     *
     * @return
     */
    @AuthCheck(UserConstant.ADMIN_ROLE)
    @PostMapping("/list/page")
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest queryRequest) {
        // 构造查询条件
        QueryWrapper<Picture> queryWrapper = pictureService.queryWrapper(queryRequest);
        // 构造分页条件
        if (queryRequest.getCurrent() <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页码不能小于0");
        Page<Picture> picturePage = new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize());
        pictureService.page(picturePage, queryWrapper);
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表 （封装类） （public, user, admin）
     *
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest queryRequest) {
        // 普通用户默认只能查看已过审的数据
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);

        // 空间权限校验
        Long spaceId = queryRequest.getSpaceId();
        if (!userService.isAdmin(loginUser)) {
            // 公开图库
            if (spaceId == null) {
                // 普通用户默认只能查看已过审的公开数据
                queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
                queryRequest.setNullSpaceId(true);
            } else {
                // 私有空间
                Space space = spaceService.getById(spaceId);
                ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
                if (!loginUser.getId().equals(space.getUserId())) {
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
                }
            }
        }
        // 构造查询条件
        QueryWrapper<Picture> queryWrapper = pictureService.queryWrapper(queryRequest);
        // 构造分页条件
        if (queryRequest.getCurrent() <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页码不能小于0");
        // 限制爬虫
        if (queryRequest.getPageSize() > 20)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页码大小过大");
        // 封装VO
        Page<Picture> picturePage = new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize());

        pictureService.page(picturePage, queryWrapper);
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage);
        return ResultUtils.success(pictureVOPage);
    }
    /**
     * 分页获取图片列表 （封装类） （public, user, admin）
     * 二级缓存（先从本地缓存获取，未命中再从远程缓存【redis】中获取，都未未命中再查询数据库并刷新缓存）
     *
     * @return
     */
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest queryRequest) {
        //定义缓存key
        String requestJson = JSONUtil.toJsonStr(queryRequest);
        String cacheKey = String.format("PicSpace:listPictureVOByPage:%s",
                DigestUtils.md5DigestAsHex(requestJson.getBytes()));
        // 1. 先从缓存中获取数据
        String cacheValue = cacheUtils.getCacheValue(cacheKey);
        if (StrUtil.isNotBlank(cacheValue)) {
            Page<PictureVO> cacheData = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cacheData);
        }
        // 普通用户默认只能查看已过审的数据
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        if (!userService.isAdmin(loginUser)) {
            queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        }
        // 构造查询条件
        QueryWrapper<Picture> queryWrapper = pictureService.queryWrapper(queryRequest);
        // 构造分页条件
        if (queryRequest.getCurrent() <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页码不能小于0");
        // 限制爬虫
        if (queryRequest.getPageSize() > 20)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页码大小过大");
        // 封装VO
        Page<Picture> picturePage = new Page<>(queryRequest.getCurrent(), queryRequest.getPageSize());

        pictureService.page(picturePage, queryWrapper);
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage);
        // 2. 缓存未命中，查询数据库，并刷新缓存
        cacheUtils.setCacheValue(cacheKey, JSONUtil.toJsonStr(pictureVOPage));
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 编辑图片信息（用户可用） （user, admin）
     *
     * @return
     */
    @AuthCheck(UserConstant.DEFAULT_ROLE)
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest editRequest) {
        ThrowUtils.throwNotNull(editRequest);
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        pictureService.editPicture(editRequest, loginUser);
        return ResultUtils.success(true);

    }

    @AuthCheck(UserConstant.ADMIN_ROLE)
    @PostMapping("/review")
    public BaseResponse<Boolean> doPictureReview(PictureReviewRequest reviewRequest) {
        ThrowUtils.throwNotNull(reviewRequest);
        User loginUser = ThreadLocalUtil.get(UserConstant.USER_LOGIN_STATE);
        pictureService.doPictureReview(reviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        String url = picture.getOriginalUrl();
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(url);
        return ResultUtils.success(resultList);
    }


    /**
     * 获取默认的分类，标签
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 校验id
     *
     * @param id
     */
    private void validId(Long id) {
        if (id == null || id < 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

}
